import { Response, NextFunction } from 'express';
import { AuthenticatedRequest } from '../types/auth';
import { ApiError } from '../utils/ApiError';
import { StatusCodes } from '../constants/statusCodes';
import { Role } from '@prisma/client';
import { auth } from './auth';

export type AllowedRole = Role | 'read:*' | 'write:*' | '*';

export const roleAuth = (allowedRoles: AllowedRole[]) => {
  return [
    auth,
    async (req: AuthenticatedRequest, _: Response, next: NextFunction) => {
      try {
        if (!req.user) {
          throw new ApiError(StatusCodes.UNAUTHORIZED, '未授权访问');
        }

        const hasPermission = allowedRoles.some(role => {
          if (role === '*') {
            return true;
          }

          if (role === 'read:*' && req.user?.role === Role.ADMIN) {
            return true;
          }

          if (role === 'write:*' && req.user?.role === Role.ADMIN) {
            return true;
          }

          return req.user?.role === role;
        });

        if (!hasPermission) {
          throw new ApiError(StatusCodes.FORBIDDEN, '无权访问该资源');
        }

        next();
      } catch (error) {
        next(error);
      }
    },
  ];
};
